// pages/addAddress/addAddress.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: 0, //是否显示加载中图标
    region: ['北京市', '北京市', '东城区'],
    lucky_id: '',
    draw_goods_id: ''
  },
  // 通过微信添加收货地址
  addFormWechat: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.chooseAddress({
      success: function(res) {
        var requestData = {
          token: _this.data.token,
          user_name: res.userName,
          tel_number: res.telNumber,
          province_name: res.provinceName,
          city_name: res.cityName,
          county_name: res.countyName,
          detail_info: res.detailInfo,
          add_type: 1
        }
        app.post('/User/addAddress', requestData, function(res) {
          if (res.code == 2000) {
            wx.showToast({
              title: '添加地址成功',
              icon: 'success',
              duration: 2000
            });
            wx.navigateBack({
              delta: 1
            })
          }else{
            wx.showToast({
              title: res.msg,
              icon: 'none',
              duration: 2000
            })
          }
        });
      },
      fail: function(res) {
        wx.showModal({
          title: '提示',
          content: '需要授权通讯地址哦~',
        })
      }
    })
  },
  // 当详细地址的内容发生变化时触发
  getTextNum: function(e) {
    console.log(e.detail.cursor);
    if (e.detail.cursor == 50) {
      wx.showToast({
        title: '地址填写过长',
        icon: 'none',
        duration: 2000
      })
    }
  },
  bindRegionChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },

  // 添加收货地址
  addAddress: function(e) {
    var _this = this;
    var address_id = _this.data.address_id;
    var addressInfo = e.detail.value;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    if (!address_id) {
      var requestData = {
        token: _this.data.token,
        user_name: addressInfo.user_name,
        tel_number: addressInfo.tel_number,
        province_name: addressInfo.address[0],
        city_name: addressInfo.address[1],
        county_name: addressInfo.address[2],
        detail_info: addressInfo.detail_info,
        add_type: 0
      }
    } else {
      var requestData = {
        token: _this.data.token,
        user_name: addressInfo.user_name,
        tel_number: addressInfo.tel_number,
        province_name: addressInfo.address[0],
        city_name: addressInfo.address[1],
        county_name: addressInfo.address[2],
        detail_info: addressInfo.detail_info,
        address_id: address_id
      }
    }

    if (requestData.user_name == "") {
      wx.showToast({
        title: "请填写收货人姓名",
        icon: "none",
        duration: 2000
      });
      return false;
    }
    if (requestData.tel_number == "") {
      wx.showToast({
        title: "请填写手机号",
        icon: "none",
        duration: 2000
      });
      return false;
    }
    if (requestData.detail_info == "") {
      wx.showToast({
        title: "请填写详细地址",
        icon: "none",
        duration: 2000
      });
      return false;
    }
    if (!address_id) {
      app.post('/User/addAddress', requestData, function(res) {
        if (res.code == 2000) {
          if (_this.data.goodsId && _this.data.btnType == 0) {
            var cookie = wx.getStorageSync('cookie');
            if (cookie && _this.data.goodsId == cookie.goods_id) {
              var orderData = {
                goods_id: cookie.goods_id,
                attr_values: cookie.selectAttributs,
                goods_num: cookie.goods_num,
                goods_money: cookie.goods_price,
                token: _this.data.token,
                version: app.setConfig.version,
                draw_goods_id: _this.data.draw_goods_id,
                lucky_id: _this.data.lucky_id
              }
              app.post('/Order/buildOrder', orderData, function(response) {
                if (response.code == 2000) {
                  wx.navigateTo({
                    url: '/pages/orderDetail/orderDetail?orderId=' + response.last_id,
                  })
                } else {
                  wx.showToast({
                    title: response.msg,
                    icon: 'none',
                    duration: 2000,
                  });
                }
              });
            } else {
              wx.showToast({
                title: '请重新下单',
                icon: 'success',
                duration: 2000,
                success: function() {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              })
            }
          } else if (_this.data.goodsId && _this.data.btnType == 1) {
            var cookie = wx.getStorageSync('cookie');
            if (cookie && _this.data.goodsId == cookie.goods_id) {
              var requestData = {
                token: _this.data.token,
                goods_id: cookie.goods_id,
                attr_values: cookie.selectAttributs,
                version: app.setConfig.version
              }
              app.post('/Goods/getGoods', requestData, function(response) {
                if (res.code == 2000) {
                  wx.navigateTo({
                    url: '/pages/orderDetail/orderDetail?orderId=' + response.last_id,
                  })
                } else {
                  wx.showToast({
                    title: response.msg,
                    icon: 'none',
                    duration: 2000,
                  });
                }
              });
            }
          } else {
            wx.showToast({
              title: '添加地址成功',
              icon: 'success',
              duration: 2000,
              success: function() {
                wx.navigateBack({
                  delta: 1
                })
              }
            })
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000
          });
        }
      });
    } else {
      app.post('/User/editAddress', requestData, function(res) {
        if (res.code == 2000) {
          if (_this.data.goodsId && _this.data.btnType == 0) {
            var cookie = wx.getStorageSync('cookie');
            if (cookie && _this.data.goodsId == cookie.goods_id) {
              var orderData = {
                goods_id: cookie.goods_id,
                attr_values: cookie.selectAttributs,
                goods_num: cookie.goods_num,
                goods_money: cookie.goods_price,
                token: _this.data.token,
                version: app.setConfig.version,
                draw_goods_id: _this.data.draw_goods_id,
                lucky_id: _this.data.lucky_id
              }
              app.post('/Order/buildOrder', orderData, function(response) {
                if (response.code == 2000) {
                  wx.navigateTo({
                    url: '/pages/orderDetail/orderDetail?orderId=' + response.last_id,
                  })
                } else {
                  wx.showToast({
                    title: response.msg,
                    icon: 'none',
                    duration: 2000,
                  });
                }
              });
            } else {
              wx.showToast({
                title: '请重新下单',
                icon: 'success',
                duration: 2000,
                success: function() {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              })
            }
          } else if (_this.data.goodsId && _this.data.btnType == 1) {
            var cookie = wx.getStorageSync('cookie');
            if (cookie && _this.data.goodsId == cookie.goods_id) {
              var requestData = {
                token: _this.data.token,
                goods_id: cookie.goods_id,
                attr_values: cookie.selectAttributs,
                version: app.setConfig.version
              }
              app.post('/Goods/getGoods', requestData, function(response) {
                if (res.code == 2000) {
                  wx.navigateTo({
                    url: '/pages/orderDetail/orderDetail?orderId=' + response.order_id,
                  })
                } else {
                  wx.showToast({
                    title: response.msg,
                    icon: 'none',
                    duration: 2000,
                  });
                }
              });
            }
          } else {
            wx.showToast({
              title: '修改地址成功',
              icon: 'success',
              duration: 2000,
              success: function() {
                wx.navigateBack({
                  delta: 1
                })
              }
            })
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000
          });
        }
      });
    }

  },
  // 获取收货地址信息
  getAddressInfo: function() {
    console.log('获取收货地址信息');
    var _this = this;
    _this.setData({
      isLoading: 1
    })
    var requestData = {
      token: _this.data.token,
      address_id: _this.data.address_id
    }
    app.post('/User/getAddress', requestData, function(res) {
      if (res.code == 2000) {
        var region = [];
        region[0] = res.data.province_name;
        region[1] = res.data.city_name;
        region[2] = res.data.county_name;
        _this.setData({
          isLoading: 0,
          addressInfo: res.data,
          region: region
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    if (options.goodsid) {
      _this.setData({
        'goodsId': options.goodsid,
        'btnType': options.buyType //0 表示直接购买 1 表示分享购买
      })
    }
    if (options.address_id) {
      _this.setData({
        address_id: options.address_id
      })
    }
    if (options.lucky_id) {
      _this.setData({
        lucky_id: options.draw_goods_id,
        draw_goods_id: options.draw_goods_id
      })
    }
    _this.loop();
  },
  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
      _this.setData({
        token: theToken
      });
      var address_id = _this.data.address_id;
      if (address_id) {
        _this.getAddressInfo();
      }
    }
  },

})